package com.gitee.sop.notify.dubbo;

import com.gitee.sop.notify.api.NotifyService;
import com.gitee.sop.notify.api.req.NotifyRequest;
import com.gitee.sop.notify.api.resp.NotifyInfoResponse;
import com.gitee.sop.notify.api.resp.NotifyResponse;
import com.gitee.sop.notify.dao.entity.NotifyInfo;
import com.gitee.sop.notify.service.NotifyBizService;
import com.gitee.sop.notify.service.bo.NotifyBO;
import com.gitee.sop.sdk.sign.SopSignException;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;


/**
 * @author 六如
 */
@DubboService(validation = "true")
@Slf4j
public class NotifyServiceImpl implements NotifyService {

    @Autowired
    private NotifyBizService notifyBizService;

    @Override
    public NotifyResponse notify(NotifyRequest request) {
        NotifyBO notifyBO = new NotifyBO();
        BeanUtils.copyProperties(request, notifyBO);
        try {
            Long notifyId = notifyBizService.notify(notifyBO);
            return NotifyResponse.success(notifyId);
        } catch (SopSignException e) {
            log.error("回调异常，服务端签名失败, request={}", request, e);
            return NotifyResponse.error(e.getErrMsg());
        }
    }

    @Override
    public NotifyResponse notifyImmediately(Long notifyId) {
        try {
            notifyBizService.notifyImmediately(notifyId);
            return NotifyResponse.success(notifyId);
        } catch (Exception e) {
            log.error("回调异常, notifyId={}", notifyId, e);
            return NotifyResponse.error(e.getMessage());
        }
    }

    @Override
    public NotifyInfoResponse getByNotifyId(Long notifyId) {
        NotifyInfo notifyInfo = notifyBizService.getById(notifyId);
        if (notifyInfo == null) {
            return null;
        }
        NotifyInfoResponse notifyInfoResponse = new NotifyInfoResponse();
        BeanUtils.copyProperties(notifyInfo, notifyInfoResponse);
        return notifyInfoResponse;
    }
}
